import os
import pandas as pd
import json
import numpy as np
from tool.data_info import DataInfo


class OpenFile(object):
    """
    打开文件类，支持类型：txt,csv,xlsx,dat,json
    """

    def __init__(self):
        super().__init__()

    def is_number(self, data):
        """
        判断数据是否是数字
        :param data:
        :return: bool
        """
        try:
            float(data)
            return True
        except ValueError:
            return False

    def read_txt(self, file_path):
        """
        txt文件导入后是str类型，很难识别出空格、标点和字母的差别
        :param file_path: 文件路径
        :return:
        """
        try:
            file_info = self.open_text(file_path)
            file_info.type = ".txt"
            return file_info
        except:
            print("文件格式错误，无法打开！！")

    def read_csv(self, file_path):
        """
        :param file_path: 文件路径
        :return: 文件信息
        """
        try:
            df = pd.read_csv(file_path)
            file_info = self.get_file_info(file_path, df)
            file_info.type = ".csv"
            return file_info
        except:
            print("文件格式错误，无法打开！！")

    def read_excel(self, file_path):
        """
        :param file_path: 文件路径
        :return: 文件信息
        """
        try:
            df = pd.read_excel(file_path, sheet_name='Sheet1')
            file_info = self.get_file_info(file_path, df)
            file_info.type = ".xlsx"
            return file_info
        except:
            print("文件格式错误，无法打开！！")

    def read_dat(self, file_path):
        """
        :param file_path: 文件路径
        :return: 文件信息
        读取文件时需要根据分割数据的符号来分开数据
        """
        try:
            file_info = self.open_text(file_path)
            file_info.type = ".dat"
            return file_info
        except:
            print("文件格式错误，无法打开！！")

    def read_json(self, file_path):
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                data = json.load(file)
                print(data)
                return data
        except:
            print("文件格式错误，无法打开！！")

    def get_file_info(self, file_path, df):
        file_info = DataInfo()
        file_info.path = file_path
        file_name = file_path.split('/')[-1]
        name = file_name.split(".")[0]
        file_info.name = name

        data = []
        aa = df.values.tolist()
        h = df.keys().to_list()
        aa.insert(0, h)
        file_cols = len(df.keys())
        file_rows = len(df[df.keys()[0]])
        file_info.cols = file_cols
        file_info.have_head = False
        for i in df.keys():
            if not self.is_number(i):
                file_info.have_head = True
        if file_info.have_head:
            file_info.rows = file_rows
            head = list(df.keys())
            file_info.head = df.keys().to_list()
            for i in range(file_cols):
                value = list(df[head[i]])  # 保存一列
                data.append(value)
            file_info.data = data
        else:
            file_info.rows = file_rows + 1
            row1 = np.float64(list(df.keys()))
            for i in range(file_cols):
                value = []
                value.append(row1[i])
                col_data = list(df[df.keys()[i]])
                value += col_data
                data.append(value)
            file_info.data = data
        return file_info

    def openfile(self, file_path):
        extension_name = file_path.split(".")[-1]
        if extension_name == 'txt':
            data = self.read_txt(file_path)
        elif extension_name == 'csv':
            data = self.read_csv(file_path)
        elif extension_name == 'xlsx':
            data = self.read_excel(file_path)
        elif extension_name == 'dat':
            data = self.read_dat(file_path)
        elif extension_name == 'json':
            data = self.read_json(file_path)
        else:
            data = DataInfo()
        return data

    def open_text(self, filepath):
        file_info = DataInfo()
        file_info.path = filepath
        file_name = filepath.split('/')[-1]
        name = file_name.split(".")[0]
        file_info.name = name
        z_data = []
        rows_count = 0
        cols_count = 0
        with open(filepath, "r") as fr:
            lines = fr.readlines()  # 一次性读取所有文件内容
            for idx, line in enumerate(lines):
                rows_count += 1
                if idx == 0:
                    data_line = []
                    if "=" in line:
                        line = line.split("=")[1]
                    for word in line.strip().split():
                        cols_count += 1
                        word = word.strip()
                        if not self.is_number(word):
                            file_info.have_head = True
                            file_info.head = line.strip().split()
                    if not file_info.have_head:
                        data_line.append(word)
                        z_data.append(data_line)
                    else:
                        rows_count -= 1
                else:
                    data_line = []
                    for word in line.strip().split():
                        word = word.strip()
                        if word != '':
                            data_line.append(word)
                    z_data.append(data_line)
        file_info.rows = rows_count
        file_info.cols = cols_count
        file_info.data = z_data
        return file_info




if __name__ == "__main__":
    file = OpenFile()
    filepath1 = os.getcwd() + "\Test_file\example.txt"
    filepath2 = os.getcwd() + "\Test_file\sss.csv"
    filepath3 = os.getcwd() + "\Test_file\\test20231016.xlsx"
    filepath4 = os.getcwd() + "\Test_file\\11.dat"
    filepath5 = os.getcwd() + "\Test_file\ddd.json"
    filepath6 = os.getcwd() + "\Test_file\demo.dat"
    print("***********txt**************")
    txt_data = file.openfile(filepath1)
    print(txt_data.data)
    print(txt_data.head)
    print("************csv*************")
    csv_data = file.openfile(filepath2)
    print(csv_data.data)
    print(csv_data.head)
    # print("*************excel************")
    # excel_data = file.openfile(filepath3)
    # print(type(excel_data.data[0][0]))
    # print(excel_data.head)
    # # print("************dat*************")
    # dat_data = file.openfile(filepath4)
    # print(dat_data.data)
    # print(dat_data.head)
    # print("**************json***********")
    # file.openfile(filepath5)
    # data = file.open_text(filepath1)
    # print("head:    ", data.head)
    # print("data:    ", data.data)
    # print("rows:    ", data.rows)
    # print("cols:    ", data.cols)





